package com.yunglu.pa03;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class DelayView extends View {
	private static final int NUMBER_BARS = 50;
	private int[] delays;
	private int curInd;
	private int max_delay;
	private boolean array_full;
	private boolean show_data;

	private void init() {
		delays = new int[NUMBER_BARS];
		curInd = 0;
		max_delay = 0;
		array_full = false;
		show_data = false;
	}

	public DelayView(Context context) {
		super(context);
		init();
	}

	public DelayView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public DelayView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		int width = canvas.getWidth();
		int height = canvas.getHeight();
		Resources res = getResources();
		Paint bluePainter = new Paint(Paint.ANTI_ALIAS_FLAG);
		bluePainter.setColor(res.getColor(R.color.blue));
		int barDistance = width / NUMBER_BARS;
		int barWidth = barDistance / 2;
		int xcoord = width - barWidth;
		int ind = curInd - 1;
		while (ind >= 0) {
			float ycoord = (float) 0.8 * height * delays[ind] / max_delay;
			canvas.drawRect(xcoord, height - ycoord, xcoord + barWidth, height,
					bluePainter);
			ind--;
			xcoord -= barDistance;
		}
		if (array_full == true) {
			ind = NUMBER_BARS - 1;
			while (ind >= curInd) {
				float ycoord = (float) 0.8 * height * delays[ind] / max_delay;
				canvas.drawRect(xcoord, height - ycoord, xcoord + barWidth,
						height, bluePainter);
				ind--;
				xcoord -= barDistance;
			}
		}
		if (show_data == true) {
			try {
				Thread.sleep(NetworkTask.TIMER_INTERVAL);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			invalidate();
		}
	}

	public void updateValue(int val) {
		delays[curInd] = val;
		max_delay = Math.max(max_delay, val);
		curInd++;
		if (curInd >= delays.length) {
			array_full = true;
			curInd = 0;
		}
	}

	public void showData(boolean v) {
		show_data = v;
		if (show_data == true) {
			invalidate();
		}
	}
}
